package com.ruoyi.framework.security.handle;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author ruoyi
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    private static final Logger log = LoggerFactory.getLogger(LogoutSuccessHandlerImpl.class);
    
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     * 
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        String userName = null;
        String token = null;
        
        if (StringUtils.isNotNull(loginUser))
        {
            // 场景1：Token有效，正常退出
            userName = loginUser.getUsername();
            token = loginUser.getToken();
            // 删除用户缓存记录
            tokenService.delLoginUser(token);
            log.info("用户 {} 正常退出登录", userName);
        }
        else
        {
            // 场景2：Token过期或无效，尝试从JWT中获取用户名
            try {
                token = tokenService.getTokenFromRequest(request);
                if (StringUtils.isNotEmpty(token)) {
                    userName = tokenService.getUsernameFromToken(token);
                    // 尝试删除（可能已过期，删除操作是幂等的）
                    tokenService.delLoginUser(token);
                    log.info("用户 {} 在token过期后退出登录", userName);
                }
            } catch (Exception e) {
                log.warn("无法从过期token中获取用户信息: {}", e.getMessage());
                userName = "未知用户";
            }
        }
        
        // 无论token是否有效，都记录退出日志
        if (StringUtils.isNotEmpty(userName)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(
                userName, 
                Constants.LOGOUT, 
                MessageUtils.message("user.logout.success")
            ));
        }
        
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
    }
}
